import {
  fetchOrders,
  fetchOrdersCount,
} from '~/services/order/orderList';
import Dialog from 'tdesign-miniprogram/dialog/index';
import {
  baseURL
} from '../../../services/request'
import {
  getOrderList,
  cancelorder,
  confrimRecevie,
  payorder,
  adminCheckOrder,
  delevieGoods,
  getStockInfo
} from '~/services/api/order'
import {
  cosThumb
} from '~/utils/util';
import {
  adminCheckNews
} from '~/services/api/message';
Page({
  page: {
    size: 5,
    num: 1,
  },

  data: {
    waitForStock: false,
    defaultImg: "https://img1.baidu.com/it/u=415449740,540746270&fm=253&fmt=auto&app=138&f=GIF?w=500&h=500",
    emptyImg: 'https://cdn-we-retail.ym.tencent.com/miniapp/order/empty-order-list.png',
    showConfirmRecevie: false,
    title: '确认收货',
    label: '确认付款',
    payImage: '',
    payMemo: "",
    expressMemo: "",
    expressNo: "",
    wareHouseOutMemo: "",
    receiptMemo: "",
    receiptPics: "",
    memo: '',
    fileList: [],
    realFileList: [], //  真实的上传地址
    goodsListLoadStatus: 0,
    pageLoading: false,
    stockInfo: {
      // 出库详情
    },
    tabs: [{
        status: '',
        key: '',
        text: '全部'
      },
      {
        status: 1,
        text: '待付款',
        info: ''
      },
      {
        status: 2,
        text: '待审核',
        info: ''
      },
      {
        status: 3,
        text: '待备货',
        info: ''
      },
      {
        status: 4,
        text: '审核拒绝',
        info: ''
      },
      {
        status: 5,
        text: '已发货',
        info: ''
      },
      {
        status: 6,
        text: '已收获',
        info: ''
      },
      {
        status: 7,
        text: '已取消',
        info: ''
      },

    ],
    curTab: '',
    orderList: [],
    listLoading: 0,
    pullDownRefreshing: false,
    emptyImg: 'https://cdn-we-retail.ym.tencent.com/miniapp/order/empty-order-list.png',
    backRefresh: false,
    status: '',
    gridConfig: {
      column: 2,
      width: 100,
      height: 100,
    },
    type: '',
    orderKid: ''
  },
  goodListPagination: {
    pageNo: 1,
    pageSize: 10,
  },
  // 弹框处理
  closeDialog() {
    this.setData({
      showConfirmRecevie: false,
      memo: '',
      fileList: [],
      realFileList: []
    })
  },
  confirmpay(e) {
    this.setData({
      showConfirmRecevie: true,
      label: '付款备注：',
      title: '确认付款',
      type: 'pay',
      orderKid: e.currentTarget.dataset.order.id
    })
  },
  closestockDialog() {
    this.setData({
      waitForStock: false,
      stockInfo: {}
    })
  },

  // getStockInfo
  async getStockInfo(e) {
    let {
      data
    } = await getStockInfo(e.currentTarget.dataset.order.id);
    this.setData({
      waitForStock: true,
      stockInfo: data
    })
  },
  // 处理弹框操作

  async confirm() {
    if (this.data.type == 'pay') {
      let params = {
        orderKid: this.data.orderKid,
        payImage: this.data.realFileList ? this.data.realFileList.join(',') : '',
        payMemo: this.data.memo
      };
      let {
        data,
        code
      } = await payorder(params);
      let index = this.data.orderList.findIndex((el) => {
        return el.id == this.data.orderKid
      });
      if (data) {
        this.data.orderList.splice(index, 1, {
          ...this.data.orderList[index],
          status: 2
        });
        this.setData({
          orderList: this.data.orderList,
          showConfirmRecevie: false,
          memo: '',
          fileList: [],
          realFileList: []
        })
      }
    } else if (this.data.type == 'confirmReceive') {
      let params = {
        orderKid: this.data.orderKid,
        receiptPics: this.data.realFileList ? this.data.realFileList.join(',') : '',
        receiptMemo: this.data.memo
      };
      let {
        data,
        code
      } = await confrimRecevie(params);
      let index = this.data.orderList.findIndex((el) => {
        return el.id == this.data.orderKid
      });
      if (data) {
        this.data.orderList.splice(index, 1, {
          ...this.data.orderList[index],
          status: 6
        });
        this.setData({
          orderList: this.data.orderList,
          showConfirmRecevie: false,
          memo: '',
          fileList: [],
          realFileList: []
        })
      }
    }
  },
  confirmReceive(e) {
    // 确认收货
    this.setData({
      showConfirmRecevie: true,
      label: '收货备注：',
      title: '确认收货',
      type: 'confirmReceive',
      orderKid: e.currentTarget.dataset.order.id
    })
  },
  // 管理员审核订单
  checkOrder(e) {
    this.setData({
      orderKid: e.currentTarget.dataset.order.id,
      showcheckVisible: true
    });

  },
  cancelOrder(e) {
    this.setData({
      orderKid: e.currentTarget.dataset.order.id
    });
    let index = this.data.orderList.findIndex((el) => {
      return el.id == this.data.orderKid
    });
    const dialogConfig = {
      context: this,
      content: '是否确定取消订单',
      confirmBtn: '确定',
      cancelBtn: '取消',
    };
    Dialog.confirm(dialogConfig)
      .then(async () => {
        let {
          data
        } = await cancelorder({
          kid: this.data.orderKid
        })
        if (data) {
          this.data.orderList.splice(index, 1, {
            ...this.data.orderList[index],
            status: 7
          });
          this.setData({
            orderList: this.data.orderList
          })
        }

      })
      .catch(() => console.log('点击了取消'))
      .finally(() => Dialog.close());
  },

  handleRemove(e) {
    const {
      index
    } = e.detail;
    this.data['fileList'].splice(index, 1);
    this.data.realFileList.splice(index, 1);
    this.setData({
      'fileList': this.data['fileList'],
      'realFileList': this.data.realFileList
    });
  },

  // 图片上传 
  handleSuccess(e) {
    let self = this;
    let tempOrigin = [];
    const role = wx.getStorageSync('role');
    let picType = e.currentTarget.dataset.type;
    let fileList = e.detail.files;
    this.setData({
      'fileList': [...this.data['fileList'], ...fileList],
    });
    //  多图统一上传
    fileList.forEach((el) => {
      wx.uploadFile({
        url: `${baseURL}fileserver/pt/fileserver/action/upload`,
        filePath: el.url,
        name: 'file',
        header: {
          devType: 4,
          userId: role.userId,
          token: role.tokenId,
          appId: "crm_agent",
          authType: "agent"
        },
        success: function (result) {
          if (JSON.parse(result.data).code == 200) {
            const resourceUrl = JSON.parse(result.data).data.urlPath;
            tempOrigin.push(resourceUrl);
            self.setData({
              "realFileList": [...self.data.realFileList, resourceUrl]
            })
          }
        }
      })
    })
  },


  onLoad(query) {
    let status = query.status ? parseInt(query.status) : '';
    if (status != 'undefined') {
      this.setData({
        curTab: status,
        status
      })
    }
    status = this.data.tabs.map((t) => t.key).includes(status) ? status : '';
    // this.init(this.data.tabs[0].status);
    this.init(this.data.curTab || this.data.tabs[0].status);
  },

  onShow() {
    if (!this.data.backRefresh) return;
    this.onRefresh();
    this.setData({
      backRefresh: false
    });
  },

  onReachBottom() {
    if (this.data.goodsListLoadStatus === 0) {
      this.loadGoodsList();
    }
  },

  onPageScroll(e) {
    this.pullDownRefresh && this.pullDownRefresh.onPageScroll(e);
  },

  onPullDownRefresh_(e) {
    this.loadHomePage();
  },
  onPullDownRefresh() {
    this.loadHomePage();
  },
  loadHomePage() {
    wx.stopPullDownRefresh();
    this.setData({
      pageLoading: true,
    });
    this.loadGoodsList(true);
  },

  async loadGoodsList(fresh = false) {
    const role = wx.getStorageSync('role');
    const userId = role?.userId;
    console.log('loaddd')
    if (fresh) {
      wx.pageScrollTo({
        scrollTop: 0,
      });
      this.setData({
        pageLoading: false,
      });
    }
    this.setData({
      goodsListLoadStatus: 1
    });
    const pageSize = this.goodListPagination.pageSize;
    let pageIndex = this.goodListPagination.pageNo + 1;
    if (fresh) {
      pageIndex = 1;
    }
    try {
      const {
        data
      } = await getOrderList({
        "pageNo": pageIndex,
        "pageSize": pageSize,
        "param": {
          "queryDimension": 3,
          orderStatus: this.data.curTab
        }
      });
      let orderList = [];
      if (data.entities && data.entities.length) {
        orderList = (data.entities || []).map((order) => {
          return {
            id: order.kid,
            orderNo: order.orderNo,
            status: order.orderStatus,
            // 订单状态 1待支付，2已支付待审核, 3已审核通过待备货，4审核拒绝，5已发货，6确认收货，7已取消
            statusDesc: order.orderStatusName,
            payAmount: order.payAmount,
            totalAmount: order.totalAmount,
            // logisticsNo: order.logisticsVO.logisticsNo,
            createTime: order.placeTime,
            goodsList: (order.orderProductList).map((goods) => ({
              id: goods.productId,
              thumb: cosThumb(goods.productPic, 70),
              title: goods.productName,
              price: goods.price,
              unitPrice: goods.unitPrice,
              productDesc: goods.productDesc,
              num: goods.num,
              productSpec: goods.productSpec
            })),
            buttons: order.buttonVOs || [],
            groupInfoVo: order.groupInfoVo,
            expressAmount: order.expressAmount,
          };
        });
      }
      this.setData({
        orderList: fresh ? orderList : this.data.orderList.concat(orderList),
        goodsListLoadStatus: pageIndex == 1 && orderList.length < 10 ? 2 : orderList.length > 1 ? 0 : 2,
      });

      this.goodListPagination.pageSize = data.pageSize;
      this.goodListPagination.pageNo = data.pageNo;
    } catch (err) {
      this.setData({
        goodsListLoadStatus: 3
      });
    }
  },

  init(status) {
    status = status !== undefined ? status : this.data.curTab;
    this.setData({
      status,
    });
    this.refreshList(status);
  },

  async getOrderList(statusCode, reset = false) {
    // if (statusCode !== -1) params.parameter.orderStatus = statusCode;
    this.setData({
      listLoading: 1
    });
    const pageSize = this.goodListPagination.pageSize;
    let pageIndex = this.goodListPagination.pageNo + 1;
    let {
      data
    } = await getOrderList({
      "param": {
        "queryDimension": 3,
        orderStatus: statusCode,
      },
      "pageNo": 1,
      "pageSize": pageSize,
    });
    let orderList = [];
    if (data.entities && data.entities.length > 0) {
      orderList = (data.entities || []).map((order) => {
        return {
          id: order.kid,
          orderNo: order.orderNo,
          status: order.orderStatus,
          // 订单状态 1待支付，2已支付待审核, 3已审核通过待备货，4审核拒绝，5已发货，6确认收货，7已取消
          statusDesc: order.orderStatusName,
          payAmount: order.payAmount,
          totalAmount: order.totalAmount,
          // logisticsNo: order.logisticsVO.logisticsNo,
          createTime: order.placeTime,
          goodsList: (order.orderProductList).map((goods) => ({
            id: goods.productId,
            thumb: cosThumb(goods.productPic, 70),
            title: goods.productName,
            price: goods.price,
            unitPrice: goods.unitPrice,
            productDesc: goods.productDesc,
            num: goods.num,
            productSpec: goods.productSpec
          })),
          buttons: order.buttonVOs || [],
          groupInfoVo: order.groupInfoVo,
          expressAmount: order.expressAmount,
        };
      });
      this.setData({
        orderList,
        listLoading: orderList.length > 10 ? 0 : 2,
      })
      this.goodListPagination.pageSize = data.pageSize;
      this.goodListPagination.pageNo = data.pageNo;
    } else {
      this.setData({
        orderList: [],
        listLoading: 2,
        pullDownRefreshing: false
      })
    }
  },

  onReTryLoad() {
    this.getOrderList(this.data.curTab);
  },
  // 1待支付，2已支付待审核, 3已审核通过待备货，4审核拒绝，5已发货，6确认收货，7已取消
  onTabChange(e) {
    const {
      value
    } = e.detail;
    this.setData({
      status: value,
    });
    console.log(value, 'value');
    this.refreshList(value);
  },

  getOrdersCount() {
    return fetchOrdersCount().then((res) => {
      const tabsCount = res.data || [];
      const {
        tabs
      } = this.data;
      tabs.forEach((tab) => {
        const tabCount = tabsCount.find((c) => c.tabType === tab.key);
        if (tabCount) {
          tab.info = tabCount.orderNum;
        }
      });
      this.setData({
        tabs
      });
    });
  },

  refreshList(status) {
    this.page = {
      size: 10,
      num: 1,
    };
    this.setData({
      curTab: status,
      orderList: []
    });
    this.getOrderList(status, true)
  },

  onRefresh() {
    this.refreshList(this.data.curTab);
  },

  onOrderCardTap(e) {
    const {
      order
    } = e.currentTarget.dataset;
    console.log(order);
    wx.navigateTo({
      url: `/subpages/pages/order-detail/index?orderNo=${order.id}`,
    });
  },
});